package com.baomidou.ant.service.impl;

import com.baomidou.ant.entity.DrawPoints;
import com.baomidou.ant.entity.LuckDraw;
import com.baomidou.ant.entity.PrizeDiamonds;
import com.baomidou.ant.entity.PrizePoints;
import com.baomidou.ant.mapper.PrizePointsMapper;
import com.baomidou.ant.service.IDrawPointsService;
import com.baomidou.ant.service.ILuckDrawService;
import com.baomidou.ant.service.IPrizePointsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * 抽奖机制
 * 1,先得结果,抽奖纪录表中
 * 2,随机出29个奖品，把结果塞入25个，组合成30个奖品的轮播奖池，扣除抽奖费用
 * 3，轮播抽奖给用户看，其实奖品已经是第25个
 *
 * @author jobob
 * @since 2021-03-24
 */
@Service
public class PrizePointsServiceImpl extends ServiceImpl<PrizePointsMapper, PrizePoints> implements IPrizePointsService {
    @Autowired
    private ILuckDrawService luckDrawService;
    @Autowired
    private IDrawPointsService drawPointsService;


    @Override
    public List<String> handleLuckDraw(Integer userId, Integer result) {

        List<Integer> resultPool=new ArrayList<>();
        List<String> resultImage=new ArrayList<>();
        //把结果存入抽奖信息表中
        PrizePoints prizePoints=getById(result);
        LuckDraw luckDraw=new LuckDraw();
        luckDraw.setPrizeId(result);
        luckDraw.setUserId(userId);
        luckDraw.setPrizeName(prizePoints.getPrizeName());
        luckDraw.setPrizeSource("积分抽奖");
        luckDrawService.save(luckDraw);

        //抽奖积分加1
        QueryWrapper<DrawPoints> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        DrawPoints drawPoints=drawPointsService.getOne(queryWrapper);
        drawPoints.setPPoints(drawPoints.getDPoints()+1);
        drawPointsService.saveOrUpdate(drawPoints);

        //添加轮播奖池
        for(int i=0;i<=29;i++){
            //第25个是奖品
            if(i==24){
                resultPool.add(result);
                continue;
            }
            //从11个奖品（大奖除外）中随机拿一个
            Random r=new Random();
            int code = r.nextInt(11);
            if(code==0){code=1;}
            resultPool.add(code);
        }

        //图片
        for(int i:resultPool){
            PrizePoints prize=getById(i);
            resultImage.add(prize.getPrizeImage());
        }

        //返回轮播奖池
        return resultImage;
    }

}
